<?php
namespace app\admin\logic\auth;

use app\common\model\AdminMenuModel;
use app\common\model\AdminModel;
use app\common\logic\AdminBase;
use think\facade\Session;

class Menu extends AdminBase
{
    public $returnResult = true;

    public function getMenus($params)
    {
        $homeInfo = [
            'title' => '欢迎页',
            'href'  => 'page/welcome-1.html',
        ];
        $logoInfo = [
            'title' => 'HI ADMIN',
            'image' => 'images/logo.png',
        ];
        $menuInfo = $this->getMenuList(session('admin_id'));
        $systemInit = [
            'homeInfo' => $homeInfo,
            'logoInfo' => $logoInfo,
            'menuInfo' => $menuInfo,
        ];

        return json($systemInit); 
    }

    // 获取菜单列表
    private function getMenuList($uid)
    {
        $admin = AdminModel::with('group')->findArray($uid);
        // de($admin);
        if (empty($admin['group'])) {
            return [];
        }

        $groupMenus = ! empty($admin['group']['menus']) ? explode(',', $admin['group']['menus']) : [];
        
        $menuList = $this->buildMenuChild(0, AdminMenuModel::getAllOpenMenus());
        // de($admin);

        // 对权限进行处理,
        // 菜单初始化，把无权限的菜单过滤掉，然后返回给前端使用
        if ($admin['group_id'] != 1) {
            foreach ($menuList as $key => $menu) {
                foreach ($menu['child'] as $k => $m) {
                    if ( ! empty($m['child'])) {
                        foreach ($m['child'] as $k2 => $m2) {
                            if ( ! in_array($m2['id'],$groupMenus)) {
                                unset($menuList[$key]['child'][$k]['child'][$k2]);
                            }
                        }
                    }
    
                    if (empty($menuList[$key]['child'][$k]['child'])) {
                        unset($menuList[$key]['child'][$k]);
                    }else {
                        $menuList[$key]['child'][$k]['child'] = array_values($menuList[$key]['child'][$k]['child']);
                    }
                }

                if (empty($menuList[$key]['child'])) {
                    unset($menuList[$key]);
                    continue;
                }else {
                    $menuList[$key]['child'] = array_values($menuList[$key]['child']);
                }
            }
        }

        return array_values($menuList);
    }

    //递归获取子菜单
    private function buildMenuChild($pid, $menuList){
        $treeList = [];
        foreach ($menuList as $v) {
            if ($pid == $v['pid']) {
                $node = $v;
                $child = $this->buildMenuChild($v['id'], $menuList);
                if (!empty($child)) {
                    $node['child'] = $child;
                }
                // todo 后续此处加上用户的权限判断
                $treeList[] = $node;
            }
        }
        return $treeList;
    }

}